import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { Button, message, Icon, DatePicker, Modal, Input, Select } from 'antd';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { useRequest } from '@umijs/hooks';

import '@ant-design/compatible/assets/index.css';
import { overbooksummary, exportOverbooksummary, queryCityInfo} from '../service';
import styles from './index.less';

import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { confirm } = Modal
const {Option} = Select
let hiddenData = null

const SummaryTable = (props) => {
  const { data: selectData } = useRequest(queryCityInfo);
  const actionRef = useRef();
  const ref = useRef();
  
  // 切换清空搜索
  useEffect(() => {
    hiddenData = null
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  // 计算高度
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse])


  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]) // 勾选列

  const [inited, setInited] = useState(true)

  const [searchParams, setSearchParams] = useState('')

  const [exportFlag, handleExportFlag] = useState('')

  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }
  /**
   * 导出
   */
  const handleExport = () => {
    if (!exportFlag){
      message.error('表格数据为空')
      return false
    }
    const hide = message.loading('正在导出');
    let res = exportOverbooksummary(searchParams).then(res=>{
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      let elink = document.createElement('a')
      let time=moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
      elink.download = '旅客超售数据汇总报表'+time+'.xls'
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      hide();
      message.success('导出成功');
    }).catch(err => {
      console.log(err)
    });
  }

  // 搜索
  const beforeSearchSubmit = useCallback(params =>{
    moment().startOf('year').format('YYYY-MM-DD');
    params['startDate'] = params.startDate ? params.startDate.startOf('month').format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.endOf('month').format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      setSearchParams(params)
      return params
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
        setSearchParams({...hiddenData, ...params})
        return {...hiddenData, ...params}

      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          startDate: moment().startOf('year'),
          endDate: moment()
        })
        hiddenData = null
        setSearchParams(params)
        return params
      }
    }

  }, [isCollapse]);

  const columns = [
    {
      title: '年度',
      dataIndex: 'annual',
      hideInSearch: true
    },
    {
      title: '月份',
      dataIndex: 'month',
      hideInSearch: true
    },
    {
      title: '起始航站',
      dataIndex: 'org',
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '到达航站',
      dataIndex: 'dst',
      initialValue: '', //缺个默认接口服务航站
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {selectData &&
              selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      },
    },
    {
      title: '航班号',
      dataIndex: 'flightNumber',
      order: 6,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    // {
    //   title: '预计超售人数',
    //   dataIndex: 'expectOverbookNumOfPeople',
    //   hideInSearch: true
    // },
    {
      title: '超售总人数',
      dataIndex: 'overbookSummaryNumOfPeople',
      hideInSearch: true
    },
    {
      title: '改签人数',
      dataIndex: 'ticketChangeNumOfPeople',
      hideInSearch: true
    },
    {
      title: '退票人数',
      dataIndex: 'refundNumOfPeople',
      hideInSearch: true
    },
    {
      title: '实际补偿人数',
      dataIndex: 'actualCompensateNumOfPeople',
      hideInSearch: true
    },
    {
      title: '实际补偿金额',
      dataIndex: 'actualCompensateAmount',
      hideInSearch: true
    },
    {
      title: '起始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 8,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '结束日期',
      hideInTable: true,
      order: 7,
      dataIndex: 'endDate',
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        );
      },
    },
  ];

  return (
    <div>
      <ProTable
        className={`${styles.overSaleCharts} rest-pro-table-form-compact rest-pro-table-tab ${isCollapse?'':'collapse'}`}
        formRef={ref}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        scroll={{ x: 1300, y:height }}
        size='small'
        search={{
          onCollapse:val => {
            controlC(val);
            if (!val && hiddenData) {
              ref.current.setFieldsValue({
                flightNumber: hiddenData.flightNumber,
                org: hiddenData.org,
                dst: hiddenData.dst,
              })
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          }
        }}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>超售数据汇总表</span>
          </div>
        }
        actionRef={actionRef}
        rowKey="id"
        rowSelection={false}
        tableAlertRender={() => {
          return false
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode="oversaleCharts.summaryTable.export">
            <Button icon="download" type="primary"  onClick={handleExport}>
              导出
            </Button>
          </AuthComponent>
        ]}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        columns={columns}
        beforeSearchSubmit={beforeSearchSubmit}
        postData={data => {
          if (data.length > 0) {
            handleExportFlag(true)
          } else {
            handleExportFlag(false)
          }
          return data
        }}
        request={params => {
          if (!params.startDate && !params.endDate) {
            params.startDate = moment().startOf('year').format('YYYY-MM-DD');
            params.endDate = moment().endOf('month').format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment().startOf('year'),
              endDate: moment()
            })
          }

          setSearchParams(params)
          return overbooksummary(params)
        }}
      />
    </div>
  );
};

export default Form.create()(SummaryTable);
